<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/14 0014
 * Time: 15:50
 */
namespace plugins\qbt_order\model;//Demo插件英文名，改成你的插件英文就行了
use think\Model;
class OrderModel extends Model{

	/**
	 *  获取订单列表信息
	 *
	 * @access  public
	 * @param
	 *
	 * @return void
	 */
	function order_list()
	{
		$page_size=I('page_size');
		$data=I('post.');
		if(!$data){
			$data=I('get.');
		}
		/* 过滤信息 */
		$filter['order_sn'] = empty($data['order_sn']) ? '' : trim($data['order_sn']);
		$filter['consignee'] = empty($data['consignee']) ? '' : trim($data['consignee']);
		$filter['email'] = empty($data['email']) ? '' : trim($data['email']);
		$filter['address'] = empty($data['address']) ? '' : trim($data['address']);
		$filter['zipcode'] = empty($data['zipcode']) ? '' : trim($data['zipcode']);
		$filter['tel'] = empty($data['tel']) ? '' : trim($data['tel']);
		$filter['mobile'] = empty($data['mobile']) ? 0 : intval($data['mobile']);
		$filter['country'] = empty($data['country']) ? 0 : intval($data['country']);
		$filter['province'] = empty($data['province']) ? 0 : intval($data['province']);
		$filter['city'] = empty($data['city']) ? 0 : intval($data['city']);
		$filter['district'] = empty($data['district']) ? 0 : intval($data['district']);
		$filter['shipping_id'] = empty($data['shipping_id']) ? 0 : intval($data['shipping_id']);
		$filter['pay_id'] = empty($data['pay_id']) ? 0 : intval($data['pay_id']);
		$filter['order_status'] = isset($data['order_status']) ? intval($data['order_status']) : -1;
		$filter['shipping_status'] = isset($data['shipping_status']) ? intval($data['shipping_status']) : -1;
		$filter['pay_status'] = isset($data['pay_status']) ? intval($data['pay_status']) : -1;
		$filter['user_id'] = empty($data['user_id']) ? 0 : intval($data['user_id']);
		$filter['user_name'] = empty($data['user_name']) ? '' : trim($data['user_name']);
		$filter['composite_status'] = isset($data['composite_status']) ? intval($data['composite_status']) : -1;
		$filter['group_buy_id'] = isset($data['group_buy_id']) ? intval($data['group_buy_id']) : 0;

		$filter['sort_by'] = empty($data['sort_by']) ? 'add_time' : trim($data['sort_by']);
		$filter['sort_order'] = empty($data['sort_order']) ? 'DESC' : trim($data['sort_order']);

		$filter['start_time'] = empty($data['start_time']) ? '' : (strpos($data['start_time'], '-') > 0 ?  local_strtotime($data['start_time']) : $data['start_time']);
		$filter['end_time'] = empty($data['end_time']) ? '' : (strpos($data['end_time'], '-') > 0 ?  local_strtotime($data['end_time']) : $data['end_time']);

		$where ='';
		if ($filter['order_sn'])
		{
			$where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
		}
		if ($filter['consignee'])
		{
			$where .= " AND o.consignee LIKE '%" . mysql_like_quote($filter['consignee']) . "%'";
		}
		if ($filter['email'])
		{
			$where .= " AND o.email LIKE '%" . mysql_like_quote($filter['email']) . "%'";
		}
		if ($filter['address'])
		{
			$where .= " AND o.address LIKE '%" . mysql_like_quote($filter['address']) . "%'";
		}
		if ($filter['zipcode'])
		{
			$where .= " AND o.zipcode LIKE '%" . mysql_like_quote($filter['zipcode']) . "%'";
		}
		if ($filter['tel'])
		{
			$where .= " AND o.tel LIKE '%" . mysql_like_quote($filter['tel']) . "%'";
		}
		if ($filter['mobile'])
		{
			$where .= " AND o.mobile LIKE '%" .mysql_like_quote($filter['mobile']) . "%'";
		}
		if ($filter['country'])
		{
			$where .= " AND o.country = '$filter[country]'";
		}
		if ($filter['province'])
		{
			$where .= " AND o.province = '$filter[province]'";
		}
		if ($filter['city'])
		{
			$where .= " AND o.city = '$filter[city]'";
		}
		if ($filter['district'])
		{
			$where .= " AND o.district = '$filter[district]'";
		}
		if ($filter['shipping_id'])
		{
			$where .= " AND o.shipping_id  = '$filter[shipping_id]'";
		}
		if ($filter['pay_id'])
		{
			$where .= " AND o.pay_id  = '$filter[pay_id]'";
		}
		if ($filter['order_status'] != -1)
		{
			$where .= " AND o.order_status  = '$filter[order_status]'";
		}
		if ($filter['shipping_status'] != -1)
		{
			$where .= " AND o.shipping_status = '$filter[shipping_status]'";
		}
		if ($filter['pay_status'] != -1)
		{
			$where .= " AND o.pay_status = '$filter[pay_status]'";
		}
		if ($filter['user_id'])
		{
			$where .= " AND o.user_id = '$filter[user_id]'";
		}
		if ($filter['user_name'])
		{
			$where .= " AND u.user_name LIKE '%" . mysql_like_quote($filter['user_name']) . "%'";
		}
		if ($filter['start_time'])
		{
			$where .= " AND o.add_time >= '$filter[start_time]'";
		}
		if ($filter['end_time'])
		{
			$where .= " AND o.add_time <= '$filter[end_time]'";
		}

		//综合状态
		switch($filter['composite_status'])
		{
			case CS_AWAIT_PAY :
				//$where .= order_query_sql('await_pay');
				$where .= " and  o.pay_status!=2  and o.order_status in (1,5,6,0)  and o.order_status!=4  ";
				break;

			case CS_AWAIT_SHIP :
				//$where .= order_query_sql('await_ship');
				$where .= " and o.order_status in (1,5,6)  and  (o.shipping_status=0   or  o.shipping_status=3 )   and  o.pay_status=2  ";
				break;

			case CS_FINISHED :
				//$where .= order_query_sql('finished');
				$where .= " and  ( o.pay_status=2  and o.shipping_status=2  and o.order_status in (1,5,6)  or  o.order_status=4 ) ";
				break;

			case PS_PAYING :
				if ($filter['composite_status'] != -1)
				{
					$where .= " AND o.pay_status = '$filter[composite_status]' ";
				}
				break;
			case OS_SHIPPED_PART :
				if ($filter['composite_status'] != -1)
				{
					$where .= " AND o.shipping_status  = '$filter[composite_status]'-2 ";
				}
				break;
			default:
//				if ($filter['composite_status'] != -1)
//				{
//					$where .= " AND o.order_status = '$filter[composite_status]' ";
//				}
		}

		/* 团购订单 */
		if ($filter['group_buy_id'])
		{
			$where .= " AND o.extension_code = 'group_buy' AND o.extension_id = '$filter[group_buy_id]' ";
		}

		/* 分页大小 */
		$p=I('p');
		$filter['p'] = empty($p) || (intval($p) <= 0) ? 1 : intval($p);

		if (isset($page_size) && intval($page_size) > 0)
		{
			$filter['page_size'] = intval($page_size);
		}else
		{
			$filter['page_size'] = C('LIST_ROWS');
		}

		if($where){

			$where=substr($where,4);
		}

		/* 记录总数 */
		if ($filter['user_name'])
		{
			$filter['record_count'] = M('order_info')->alias('o')->left("__USERS__ u on o.user_id=u.user_id","LEFT")->where($where)->count();
		}
		else
		{
			$filter['record_count'] = M('order_info')->alias('o')->where($where)->count();
		}
		$filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;
		/* 查询 */
		if($where){
			$where=" where ".$where;
		}
		$sql = "SELECT o.order_id,o.user_id,o.card_id, o.order_sn, o.add_time, o.order_status, o.shipping_status, o.order_amount, o.money_paid," .
			"o.pay_status, o.consignee, o.address, o.email, o.tel, o.extension_code, o.extension_id, " .
			"(" .order_amount_field('o.') . ") AS total_fee, " .
			"IFNULL(u.user_name, '匿名用户') AS buyer ".
			" FROM " . C('DB_PREFIX').'order_info' . " AS o " .
			" LEFT JOIN " .C('DB_PREFIX').'users'. " AS u ON u.user_id=o.user_id ". $where .
			" ORDER BY $filter[sort_by] $filter[sort_order] ".
			" LIMIT " . ($filter['p'] - 1) * $filter['page_size'] . ",$filter[page_size]";
		foreach (array('order_sn', 'consignee', 'email', 'address', 'zipcode', 'tel', 'user_name') AS $val)
		{
			$filter[$val] = stripslashes($filter[$val]);
		}

		$row = M()->query($sql);
		/* 格式话数据 */
		foreach ($row AS $key => $value)
		{
			$row[$key]['formated_order_amount'] = price_format($value['order_amount']);
			$row[$key]['formated_money_paid'] = price_format($value['money_paid']);
			$row[$key]['formated_total_fee'] = price_format($value['total_fee']);
			$row[$key]['short_order_time'] = local_date('m-d H:i', $value['add_time']);
			if ($value['order_status'] == OS_INVALID || $value['order_status'] == OS_CANCELED)
			{
				/* 如果该订单为无效或取消则显示删除链接 */
				$row[$key]['can_remove'] = 1;
			}
			else
			{
				$row[$key]['can_remove'] = 0;
			}
		}
		$arr = array('orders' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);

		return $arr;
	}



	/**
	 * 返回某个订单可执行的操作列表，包括权限判断
	 * @param   array   $order      订单信息 order_status, shipping_status, pay_status
	 * @param   bool    $is_cod     支付方式是否货到付款
	 * @return  array   可执行的操作  confirm, pay, unpay, prepare, ship, unship, receive, cancel, invalid, return, drop
	 * 格式 array('confirm' => true, 'pay' => true)
	 */
	function operable_list($order)
	{
		/* 取得订单状态、发货状态、付款状态 */
		$os = $order['order_status'];
		$ss = $order['shipping_status'];
		$ps = $order['pay_status'];
		/* 取得订单操作权限 */

		$priv_list  = array('os' => true, 'ss' => true, 'ps' => true, 'edit' => true);

		/* 取得订单支付方式是否货到付款 */
		$payment = payment_info($order['pay_id']);
		$is_cod  = $payment['is_cod'] == 1;

		/* 根据状态返回可执行操作 */
		$list = array();
		if (OS_UNCONFIRMED == $os)
		{
			/* 状态：未确认 => 未付款、未发货 */
			if ($priv_list['os'])
			{
				$list['confirm']    = true; // 确认
				$list['invalid']    = true; // 无效
				$list['cancel']     = true; // 取消
				if ($is_cod)
				{
					/* 货到付款 */
					if ($priv_list['ss'])
					{
						$list['prepare'] = true; // 配货
						$list['split'] = true; // 分单
					}
				}
				else
				{
					/* 不是货到付款 */
					if ($priv_list['ps'])
					{
						$list['pay'] = true;  // 付款
					}
				}
			}
		}
		elseif (OS_CONFIRMED == $os || OS_SPLITED == $os || OS_SPLITING_PART == $os)
		{
			/* 状态：已确认 */
			if (PS_UNPAYED == $ps)
			{
				/* 状态：已确认、未付款 */
				if (SS_UNSHIPPED == $ss || SS_PREPARING == $ss)
				{
					/* 状态：已确认、未付款、未发货（或配货中） */
					if ($priv_list['os'])
					{
						$list['cancel'] = true; // 取消
						$list['invalid'] = true; // 无效
					}
					if ($is_cod)
					{
						/* 货到付款 */
						if ($priv_list['ss'])
						{
							if (SS_UNSHIPPED == $ss)
							{
								$list['prepare'] = true; // 配货
							}
							$list['split'] = true; // 分单
						}
					}
					else
					{
						/* 不是货到付款 */
						if ($priv_list['ps'])
						{
							$list['pay'] = true; // 付款
						}
					}
				}
				/* 状态：已确认、未付款、发货中 */
				elseif (SS_SHIPPED_ING == $ss || SS_SHIPPED_PART == $ss)
				{
					// 部分分单
					if (OS_SPLITING_PART == $os)
					{
						$list['split'] = true; // 分单
					}
					$list['to_delivery'] = true; // 去发货
				}
				else
				{
					/* 状态：已确认、未付款、已发货或已收货 => 货到付款 */
					if ($priv_list['ps'])
					{
						$list['pay'] = true; // 付款
					}
					if ($priv_list['ss'])
					{
						if (SS_SHIPPED == $ss)
						{
							$list['receive'] = true; // 收货确认
						}
						$list['unship'] = true; // 设为未发货
						if ($priv_list['os'])
						{
							$list['return'] = true; // 退货
						}
					}
				}
			}
			else
			{
				/* 状态：已确认、已付款和付款中 */
				if (SS_UNSHIPPED == $ss || SS_PREPARING == $ss)
				{
					/* 状态：已确认、已付款和付款中、未发货（配货中） => 不是货到付款 */
					if ($priv_list['ss'])
					{
						if (SS_UNSHIPPED == $ss)
						{
							$list['prepare'] = true; // 配货
						}
						//$list['split'] = true; // 分单 edit by tiankong 取消分单
					}
					if ($priv_list['ps'])
					{
						$list['unpay'] = true; // 设为未付款
						if ($priv_list['os'])
						{
							$list['cancel'] = true; // 取消
						}
					}
				}
				/* 状态：已确认、未付款、发货中 */
				elseif (SS_SHIPPED_ING == $ss || SS_SHIPPED_PART == $ss)
				{
					// 部分分单
					if (OS_SPLITING_PART == $os)
					{
						//$list['split'] = true; // 分单  edit by tiankong 取消分单
					}
					$list['to_delivery'] = true; // 去发货
				}
				else
				{
					/* 状态：已确认、已付款和付款中、已发货或已收货 */
					if ($priv_list['ss'])
					{
						if (SS_SHIPPED == $ss)
						{
							$list['receive'] = true; // 收货确认
						}
						if (!$is_cod)
						{
							$list['unship'] = true; // 设为未发货
						}
					}
					if ($priv_list['ps'] && $is_cod)
					{
						$list['unpay']  = true; // 设为未付款
					}
					if ($priv_list['os'] && $priv_list['ss'] && $priv_list['ps'])
					{
						$list['return'] = true; // 退货（包括退款）
					}
				}
			}
		}
		elseif (OS_CANCELED == $os)
		{
			/* 状态：取消 */
			if ($priv_list['os'])
			{
				$list['confirm'] = true;
			}
			if ($priv_list['edit'])
			{
				$list['remove'] = true;
			}
		}
		elseif (OS_INVALID == $os)
		{
			/* 状态：无效 */
			if ($priv_list['os'])
			{
				$list['confirm'] = true;
			}
			if ($priv_list['edit'])
			{
				$list['remove'] = true;
			}
		}
		elseif (OS_RETURNED == $os)
		{
			/* 状态：退货 */
			if ($priv_list['os'])
			{
				$list['confirm'] = true;
			}
		}

		/* 修正发货操作 */
		if (!empty($list['split']))
		{
			/* 如果部分发货 不允许 取消 订单 */
//			$bufen_fahuo=$this->order_deliveryed($order['order_id']);
//			if ($bufen_fahuo)
//			{
//				$list['return'] = true; // 退货（包括退款）
//				unset($list['cancel']); // 取消
//			}
		}

		/* 售后 */ //取消售后
		//$list['after_service'] = true;

		return $list;
	}


	/**
	 * 判断订单是否已发货（含部分发货）
	 * @param   int     $order_id  订单 id
	 * @return  int     1，已发货；0，未发货
	 */
	function order_deliveryed($order_id)
	{
		$return_res = 0;

		if (empty($order_id))
		{
			return $return_res;
		}

		$sum=M('delivery_order')->where(" order_id='$order_id' and status = 0 ")->count();
		if ($sum)
		{
			$return_res = 1;
		}

		return $return_res;
	}


	/**
	 * 取得订单商品
	 * @param   array     $order  订单数组
	 * @return array
	 */
	function get_order_goods($order)
	{
		$goods_list = array();
		$goods_attr = array();
		$sql = "SELECT o.*, g.suppliers_id AS suppliers_id,IF(o.product_id > 0, p.product_number, g.goods_number) AS storage, o.goods_attr, IFNULL(b.brand_name, '') AS brand_name, p.product_sn " .
			"FROM " . C('DB_PREFIX').'order_goods' . " AS o ".
			"LEFT JOIN " . C('DB_PREFIX').'products' . " AS p ON o.product_id = p.product_id " .
			"LEFT JOIN " . C('DB_PREFIX').'goods' . " AS g ON o.goods_id = g.goods_id " .
			"LEFT JOIN " . C('DB_PREFIX').'brand' . " AS b ON g.brand_id = b.brand_id " .
			"WHERE o.order_id = '$order[order_id]' ";
		$res = M()->query($sql);
		foreach($res as $row)
		{

			$row['formated_subtotal']       = price_format($row['goods_price'] * $row['goods_number']);
			$row['formated_goods_price']    = price_format($row['goods_price']);

			$goods_attr[] = explode(' ', trim($row['goods_attr'])); //将商品属性拆分为一个数组

			if ($row['extension_code'] == 'package_buy')
			{
				$row['storage'] = '';
				$row['brand_name'] = '';

			}

			//处理货品id
			$row['product_id'] = empty($row['product_id']) ? 0 : $row['product_id'];

			$goods_list[] = $row;
		}

		$attr = array();
		$arr  = array();
		foreach ($goods_attr AS $index => $array_val)
		{
			foreach ($array_val AS $value)
			{
				$arr = explode(':', $value);//以 : 号将属性拆开
				$attr[$index][] =  @array('name' => $arr[0], 'value' => $arr[1]);
			}
		}

		return array('goods_list' => $goods_list, 'attr' => $attr);
	}


	/**
	 * 删除订单所有相关单子
	 * @param   int     $order_id      订单 id
	 * @param   int     $action_array  操作列表 Array('delivery', 'back', ......)
	 * @return  int     1，成功；0，失败
	 */
	function del_delivery($order_id, $action_array)
	{
		//$return_res = 0;
		$return_res = 1;
		return $return_res;
		if (empty($order_id) || empty($action_array))
		{
			return $return_res;
		}

		$query_delivery = 1;
		$query_back = 1;
		if (in_array('delivery', $action_array))
		{
			$sql = 'DELETE O, G
                FROM ' . C('DB_PREFIX').'delivery_order' . ' AS O, ' .C('DB_PREFIX').'delivery_goods'. ' AS G
                WHERE O.order_id = \'' . $order_id . '\'
                AND O.delivery_id = G.delivery_id';
			$query_delivery=M()->execute($sql);
		}
		if (in_array('back', $action_array))
		{
			$sql = 'DELETE O, G
                FROM ' .C('DB_PREFIX').'back_order' . ' AS O, ' . C('DB_PREFIX').'back_goods' . ' AS G
                WHERE O.order_id = \'' . $order_id . '\'
                AND O.back_id = G.back_id';
			$query_back=M()->execute($sql);
		}

		if ($query_delivery && $query_back)
		{
			$return_res = 1;
		}

		return $return_res;
	}


	/**
	 * 退回余额、积分、红包（取消、无效、退货时），把订单使用余额、积分、红包设为0
	 * @param   array   $order  订单信息
	 */
	function return_user_surplus_integral_bonus($order)
	{
		/* 处理余额、积分、红包 */
		if ($order['user_id'] > 0 && $order['surplus'] > 0)
		{
			$surplus = $order['money_paid'] < 0 ? $order['surplus'] + $order['money_paid'] : $order['surplus'];
			log_account_change($order['user_id'], $surplus, 0, 0, 0, sprintf('由于取消、无效或退货操作，退回支付订单 %s 时使用的预付款', $order['order_sn']));
			M()->execute("UPDATE ". C('DB_PREFIX').'order_info' . " SET `order_amount` = '0' WHERE `order_id` =". $order['order_id']);
		}

		if ($order['user_id'] > 0 && $order['integral'] > 0)
		{
			log_account_change($order['user_id'], 0, 0, 0, $order['integral'], sprintf( '由于取消、无效或退货操作，退回支付订单 %s 时使用的积分', $order['order_sn']));
		}

		if ($order['bonus_id'] > 0)
		{
			unuse_bonus($order['bonus_id']);
		}

		if($order['discount'] && $order['card_id']){

			//退还年卡
			$study_member_info=M('study_member')->where("id=".$order['card_id']." and user_id=".$order['user_id'])->find();
			if($study_member_info['id']){

				M('study_member')->where("id=".$order['card_id'])->setInc('money',$order['discount']);
			}


		}

		/* 修改订单 */
		$arr = array(
			'bonus_id'  => 0,
			'bonus'     => 0,
			'integral'  => 0,
			'integral_money'    => 0,
			'discount'    => 0, //将年卡金额清0
			'surplus'   => 0
		);
		update_order($order['order_id'], $arr);
	}


	/**
	 * 更新订单总金额
	 * @param   int     $order_id   订单id
	 * @return  bool
	 */
	function update_order_amount($order_id)
	{
		//更新订单总金额
		$sql = "UPDATE " . C('DB_PREFIX').'order_info' .
			" SET order_amount = " . order_due_field() .
			" WHERE order_id = '$order_id' LIMIT 1";

		return M()->execute($sql);
	}

	/**
	 * 删除发货单(不包括已退货的单子)
	 * @param   int     $order_id  订单 id
	 * @return  int     1，成功；0，失败
	 */
	function del_order_delivery($order_id)
	{
		$return_res = 0;

		if (empty($order_id))
		{
			return $return_res;
		}

		$sql = 'DELETE O, G
            FROM ' . C('DB_PREFIX').'delivery_order' . ' AS O, ' . C('DB_PREFIX').'delivery_goods' . ' AS G
            WHERE O.order_id = \'' . $order_id . '\'
            AND O.status = 0
            AND O.delivery_id = G.delivery_id';
		$query = M()->execute($sql);

		if ($query)
		{
			$return_res = 1;
		}

		return $return_res;
	}


	/**
	 * 处理编辑订单时订单金额变动
	 * @param   array   $order  订单信息
	 * @param   array   $msgs   提示信息
	 * @param   array   $links  链接信息
	 */
	function handle_order_money_change($order, &$msgs, &$links)
	{

		return true;
	}



	/**
	 * 更新订单对应的 pay_log
	 * 如果未支付，修改支付金额；否则，生成新的支付log
	 * @param   int     $order_id   订单id
	 */
	function update_pay_log($order_id)
	{
		$order_id = intval($order_id);
		if ($order_id > 0)
		{
			$order_amount =M('order_info')->where(" order_id = '$order_id' ")->getField('order_amount');
			if (!is_null($order_amount))
			{
				$log_id=M('pay_log')->where("order_id = '$order_id'" . " AND order_type = '" . PAY_ORDER . "'" . " AND is_paid = 0")->getField('log_id');
				if ($log_id > 0)
				{
					/* 未付款，更新支付金额 */
					$sql = "UPDATE " .C('DB_PREFIX').'pay_log' .
						" SET order_amount = '$order_amount' " .
						"WHERE log_id = '$log_id' LIMIT 1";
				}
				else
				{
					/* 已付款，生成新的pay_log */
					$sql = "INSERT INTO " . C('DB_PREFIX').'pay_log' .
						" (order_id, order_amount, order_type, is_paid)" .
						"VALUES('$order_id', '$order_amount', '" . PAY_ORDER . "', 0)";
				}
				M()->execute($sql);
			}
		}
	}

}

?>
